package com.zwq.util;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class BaiduTokenUtil {

    @Value("${baidu.api.auth-url}")
    private String AUTH_URL;

    @Value("${baidu.api.key}")
    private String API_KEY;

    @Value("${baidu.api.secret}")
    private String SECRET_KEY;

    private final RestTemplate restTemplate;

    public BaiduTokenUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String getAccessToken() {
        String url = AUTH_URL
                + "?grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY;

        String response = restTemplate.postForObject(url, null, String.class);

        if (response == null) {
            throw new RuntimeException("Failed to get access token: response is null");
        }
        return parseAccessToken(response);
    }

    private static String parseAccessToken(String response) {
        return response.split("\"access_token\":\"")[1].split("\"")[0];
    }
}